package DBLayer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import ModelLayer.*;


public class DBCustomer 
{
	private Connection con;
    private PreparedStatement pStmtSelect;
    // Creates a new instance of DBCustomer
    public DBCustomer()
    {
    	con = DBConnection.getInstance().getDBcon();
    }
    //bygger en kunde ud fra nogle resultater.
	   private Person buildCustomer(ResultSet results)
	    {
	    	Person cust = new Customer();
	       
	         try
	         {
	               cust.setId(results.getInt("id_"));
	               cust.setName(results.getString("name"));
	               cust.setAddress(results.getString("address"));
	               cust.setPhoneNo(results.getInt("phoneNo"));
	               cust.setEmail(results.getString("email"));
	               cust.setCountry(results.getString("country"));
	               cust.setRights(results.getString("users"));
	               
	               
	               
	               
	         }
	         catch(Exception e)
	         {
	             System.out.println("der skete en fejl");
	         }
	        
	        return cust;
	        
	        
	    }
	   
	   // finder kunden ud fra et kunde id.
	   public Person findCustomer(int cid, boolean retriveAssociation)
       {
		  
			String wClause = "  id_ = '" +cid + "'";
			return singleWhere(wClause, retriveAssociation);
       }
	
	  
	  private Person singleWhere(String wClause, boolean retrieveAssociation) {
			ResultSet results;
			Person cust = new Customer();

			String query = buildQuery(wClause);
			System.out.println(query);
			try { // read the customer from the database
				Statement stmt = con.createStatement();
				stmt.setQueryTimeout(5);
				results = stmt.executeQuery(query);

				if (results.next()) {
					
					cust = buildCustomer(results);
					// assocaition is to be build
					stmt.close();


					
				} 
				else 
				{ // no customers was found
					System.out.println("hej1");
					cust = null;
				}
			}// end try
			catch (Exception e) 
			{
				System.out.println("Query exception: " + e);
			}
			return cust;
		}
	  
	  private String buildQuery(String wClause) 
	  {
			String query = "SELECT id_, name, address, phoneNo, Email, country, users, zipcode FROM Customer";
	        if (wClause.length() > 0)
	        {
				query = query + " WHERE " + wClause;
	        }
	        return query;
	  }

}
